package com.sp.app.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.sp.app.domain.Notice;
import com.sp.app.domain.User;
import com.sp.app.service.NoticeService;
import com.sp.app.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/Notice")
public class NoticeController {

	@Autowired
	private NoticeService noticeService;

	@RequestMapping("/add")
	public String toAdd(){
		return "NoticeAdd";
	}


	@RequestMapping("/modify")
	public String modify(HttpServletRequest request,Notice notice){
		List<Notice> noticeList = noticeService.queryAll(notice);
		request.setAttribute("list",noticeList);
		return "noticeModfiy";
	}

	@RequestMapping("/update")
	public String update(HttpServletRequest request,Notice notice){
		User user = (User) request.getSession().getAttribute("user");
		notice.setUserid(user.getId());
		notice.setCreatdate(DateUtil.getStringToday());
		noticeService.update(notice);
		return "redirect:/Notice/modify";
	}

	@RequestMapping("/delete")
	public String delete(HttpServletRequest request,Notice notice){
		List<Notice> noticeList = noticeService.queryAll(notice);
		request.setAttribute("list",noticeList);
		return "noticeDelete";
	}

	@RequestMapping("/delete1")
	public String delete1(String ID){
		noticeService.delete(ID);
		return "redirect:/Notice/delete";
	}

	@ResponseBody
	@RequestMapping("/queryOne")
	public String queryOne(String id){
		System.out.println("=================="+id);

		Notice notice = new Notice();
		notice.setId(id);
		List<Notice> noticeList = noticeService.queryAll(notice);
		JSONObject json = new JSONObject();
		return json.toJSONString(noticeList.get(0));
	}


	@RequestMapping("/add1")
	public String  add(HttpServletRequest request,String Content,String biaoti) throws Exception{
		User user = (User) request.getSession().getAttribute("user");
		Notice notice = new Notice();
		notice.setContent(Content);
		notice.setTitle(biaoti);
		notice.setCreatdate(DateUtil.Date2String(new Date()));
		notice.setId(String.valueOf(Math.random()).substring(2, 8));
		notice.setUserid(user.getId());
		noticeService.add(notice);

		return "redirect:/User/Main";
	}
}
